package com.msmall.community.tag.bbs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.cache.CacheFactory;
import com.msmall.base.util.Constants;
import com.msmall.community.ApplicationManager;
import com.msmall.community.bbs.model.Board;
import com.msmall.community.bbs.model.Topic;
import com.msmall.community.bbs.service.BoardManager;
import com.msmall.community.common.CascadeCollection;

public class BbsTag extends TagSupport {

	private static final long serialVersionUID = -6589428183645363221L;
	
	private static final Log logger = LogFactory.getLog(BbsTag.class);
	
	private String type;
	
	private String property;
	
	public int doStartTag() throws JspException {
		return (SKIP_BODY);
	}

	public int doEndTag() throws JspException {
		JspWriter writer = pageContext.getOut();
		String message = "";
		try {
			if("boardname".equalsIgnoreCase(type)){ //通过ID查找版区中文名称
				Board board = getBoard(Long.valueOf(property));
				if(board == null){
					message = "顶级版区";
				}else{
					message = board.getChineseName();
				}
			}
			if("boardnameall".equalsIgnoreCase(type)){ //通过ID查找版区中文名称
				message = getBoardNameByTopicid(true);
			}
			if("selectparentboard".equalsIgnoreCase(type)){ //为某个版区选择父版区
				StringBuffer buffer = new StringBuffer();
				List<Board> boards = this.getAllAvailableBoard();
				Board boardx = null;
				Long parentId = null;
				if(null != property && !"".equals(property.trim())){
					boardx = this.getBoard(Long.valueOf(property));
					parentId = boardx.getParentId();
				}
				buffer.append("<option value=\"0\">顶级版区</option>");
				for(int i = 0; i < boards.size(); i++){
					Board board = boards.get(i);
					if(String.valueOf(board.getBoardId()).equals(property)){
						continue;
					}
					buffer.append("<option value=\"")
						.append(board.getBoardId())
						.append("\"");
					if(null != parentId){
						if(board.getBoardId().compareTo(parentId) == 0){
							buffer.append("selected=\"selected\"");
						}
					}
					buffer.append(">")
						.append(board.getChineseName())
					.append("</option>");
				}
				message = buffer.toString();
			}
			if("allboards".equalsIgnoreCase(type)){ //所有版区列表
				StringBuffer buffer = new StringBuffer();
				List<Board> boards = this.getAllAvailableBoard();
				for(int i = 0; i < boards.size(); i++){
					Board board = boards.get(i);
					if(!StringUtils.isBlank(property)){
						Long bid = Long.valueOf(property);
						if(bid.compareTo(board.getBoardId()) == 0){
							buffer.append("<option value=\"")
							.append(board.getBoardId())
							.append("\" selected=\"selected\">")
							.append(board.getChineseName())
						.append("</option>");
						}
					}
					buffer.append("<option value=\"")
						.append(board.getBoardId())
						.append("\">")
						.append(board.getChineseName())
					.append("</option>");
				}
				message = buffer.toString();
			}
			if("excludeboards".equalsIgnoreCase(type)){ //排除部分版区后的版区列表，排除部分用，分割
				StringBuffer buffer = new StringBuffer();
				List<Board> boards = this.getAllAvailableBoard();
				String[] excludes = null;
				if(null != property && !"".equals(property.trim())){
					excludes = property.split(",");
				}
				for(int i = 0; i < boards.size(); i++){
					Board board = boards.get(i);
					boolean tag = false;
					if(excludes != null){
						for(int j = 0; j < excludes.length; j++){
							if(String.valueOf(board.getBoardId()).equals(excludes[j])){
								tag = true;
								break;
							}
						}
					}
					if(tag){
						continue;
					}
					buffer.append("<option value=\"")
						.append(board.getBoardId())
						.append("\">")
						.append(board.getChineseName())
					.append("</option>");
				}
				message = buffer.toString();
			}
			writer.print(message);
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		return (SKIP_BODY);
	}

	private Board getBoard(Long boardId){
		CascadeCollection<Board> cs = (CascadeCollection<Board>) CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON).get(Constants.CACHE_KEY_BBS_BOARD_CASCADECOLLECTION);
		if(cs.getAllDatas().get(boardId) != null){
			return cs.getAllDatas().get(boardId).getCurrent();
		}else{
			return null;
		}
	}
	private String getBoardNameByTopicid(boolean all){
		try {
			CascadeCollection<Board> cs = (CascadeCollection<Board>) CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON).get(Constants.CACHE_KEY_BBS_BOARD_CASCADECOLLECTION);
			BoardManager manager = (BoardManager) ApplicationManager.appContext.getBean("boardManager");
			Topic topic = (Topic) manager.get(Topic.class, Long.valueOf(property));
			Long boardid = topic.getBoardid();
			CascadeCollection<Board> current = cs.getAllDatas().get(boardid);
			if(all){
				if(current.getParents()!=null && current.getFirstParent() != null){
					CascadeCollection<Board> parent = current.getFirstParent();
					return parent.getCurrent().getChineseName() + "==>" + current.getCurrent().getChineseName();
				}
			}
			return current.getCurrent().getChineseName();
		} catch (Exception e) {
			logger.debug(e);
		}
		return "";
	}
	private List<Board> getAllAvailableBoard(){
		List<Board> boards = getAllBoard();
		for(int i = 0; i < boards.size(); i ++){
			Board board = boards.get(i);
			if(board.getEnabled().compareTo((short)0) == 0){
				boards.remove(i);
			}
		}
		return boards;
	}
	private List<Board> getAllBoard(){
		List<Board> list = new ArrayList<Board>();
		CascadeCollection<Board> cs = (CascadeCollection<Board>) CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON).get(Constants.CACHE_KEY_BBS_BOARD_CASCADECOLLECTION);
		for(CascadeCollection<Board> c : cs.getAllDatas().values()){
			list.add(c.getCurrent());
		}
		return list;
	}
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}
}
